﻿using CPPEI.WebApi;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Demo
{
    public partial class TestUploadModule : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string tempFileName = string.Format("{0}.zip", Guid.NewGuid().ToString("N"));
            string tempFilePath = Server.MapPath(string.Format("~/upload_temp/{0}", tempFileName));
            FileUpload1.SaveAs(tempFilePath);

            string moduleAssemblyShortName = null;
            using (Stream stream = CPPEI.WebApi.Packaging.PackageUtil.ReadFile(tempFilePath, "/_module.xml"))
            {
                CPPEI.WebApi.Packaging.ModuleDef module = CPPEI.WebApi.Packaging.ModuleDefDocument.Load(stream);

                moduleAssemblyShortName = new AssemblyName(module.Assembly).Name;
                // 更新配置文件
                CPPEI.WebApi.Config newConfig = Config.Current.Clone();
                if(newConfig.GetModule(module.Name) == null)
                {
                    newConfig.Modules.Add(Config.Module.Build(module));
                }
                else
                {
                    newConfig.UpdateModule(Config.Module.Build(module));
                }

                CPPEI.WebApi.ConfigDocument.Save(newConfig, Server.MapPath("~/configs/webapi.config"));
            }
            // 解压文件
            string uncompressDir = Server.MapPath(string.Format("~/_logic/{0}", moduleAssemblyShortName));
            CPPEI.WebApi.Packaging.PackageUtil.Uncompress(uncompressDir, tempFilePath);
        }
    }
}